package is.server.controller.session.local.command;

import is.common.interfaces.Command;
import is.server.Conf;
import is.server.Main;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.net.BindException;

/**
 * @author aspr0
 *         Date: 06.04.12
 *         Time: 23:07
 */
public class OpenCommand implements Command
{
    private String[] params;

    public OpenCommand(String[] params)
    {
        this.params = params;
    }

    public void execute()
    {
        if (params.length < 1)
        {
            Main.getController().getUserInterface().exposeErrMsg("no file name specified"); //todo
            return;
        }

        /* command line params: dbFileName [port [controlPort]] */
        String dbFileName = params[0];
        int port = Conf.PORT;
        int controlPort = Conf.CONTROL_PORT;

        try
        {
            switch (params.length)
            {
                case 3:
                    controlPort = Integer.parseInt(params[2]);

                case 2:
                    port = Integer.parseInt(params[1]);
            }

        }
        catch (NumberFormatException e)
        {
            Main.getController().getUserInterface().exposeErrMsg("ports should be numbers"); //todo
            return;
        }

        try
        {
            Main.getController().getModel().deactivate();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (TransformerException e)
        {
            e.printStackTrace();
        }

        try
        {
            Main.getController().getModel().activate(dbFileName, port, controlPort);

            String msg = "%s file loaded and parsed, server started listening on port %s cport %s";
            Main.getController().getUserInterface()
                    .exposeInfoMsg(msg, dbFileName, port, controlPort);
        }
        catch (BindException e)
        {
            Main.getController().getUserInterface().exposeErrMsg("port(s) already in use");
//            e.printStackTrace();
        }
        catch (IOException e)
        {
            Main.getController().getUserInterface().exposeErrMsg("file couldn't be read");
//            e.printStackTrace();
        }
        catch (SAXParseException e)
        {
            Main.getController().getUserInterface().exposeErrMsg("parsing failed, check schema.xsd and db xml file");
//            e.printStackTrace();
        }
        catch (SAXException e)
        {
            e.printStackTrace();
        }
        catch (ParserConfigurationException e)
        {
            e.printStackTrace();
        }
        catch (TransformerException e)
        {
            e.printStackTrace();
        }
    }
}
